package models

import (
	"github.com/astaxie/beego/orm"
	//"github.com/astaxie/beego"
	//"time"
	//"github.com/astaxie/beego"
	"pq/helper"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

type PqUser struct {
	BaseModel
	Id       int 	`json:"id"`
	Name     string `json:"name"`
	Password string `json:"-"`
	Salt     string `json:"-"`
	Nickname string `json:"nickname"`
	Type     int 	`json:"type"`
	State    int	`json:"state"`
	Avatar string	`json:"avatar"`
	PqTestCategoryId int `json:"test_category_id"`
	AreaCode string `json:"area_code"`
	//PqTestAreaId int `json:"test_area_id"`
	//PqTestCategory  *PqTestCategory `orm:"rel(fk)";json:"category"`
}

//type PqUserFront struct {
//	BaseModel
//	Id       int 	`json:"id"`
//	Name     string `json:"name"`
//	Password string `json:"-"`
//	Salt     string `json:"-"`
//	Nickname string `json:"nickname"`
//	Type     int 	`json:"type"`
//	State    int	`json:"state"`
//	Avatar string	`json:"avatar"`
//	//PqTestCategoryId int `json:"test_category_id"`
//	PqTestCategory  *PqTestCategory `orm:"rel(fk)";json:"category"`
//}
func (this *PqUser) ListAll(q []interface{}) ([]orm.Params,interface{}) {
	var nodes []orm.Params
	model := GetSlaveDb()
	model.Raw(`select id,name,nickname,avatar,created_time,type,pq_test_category_id,state from pq_user where state > -1 order by created_time desc,type desc limit ?,?`,q).Values(&nodes)
	//amount := GetTotal(model)
	var maps []orm.Params
	//o := GetSlaveDb()
	model.Raw("select count(*) as amount from pq_user where state > -1").Values(&maps)
	return nodes,maps[0]["amount"]
}

func (this *PqUser) Create() bool{
	o := GetMasterDb()
	user := PqUser{Name:this.Name,PqTestCategoryId:0}
	err := o.Read(&user,"Name","PqTestCategoryId")
	//是否已存在
	if err != orm.ErrNoRows {
		return false
	}
	_,err = o.Insert(this)
	if err != nil {
		logs.Error(err.Error())
		return false
	}
	return true
}
func (this *PqUser) Auth(password string) (bool,PqUser) {
	o := GetSlaveDb()
	user := PqUser{Name : this.Name}
	err := o.Read(&user,"Name","Type")
	if err == nil {
		pwd,_ := helper.Decrypt(user.Password,user.Salt)
		//beego.Warning(pwd,password)
		if pwd == password {
			return true,user
		}
	}
	return false,user
}
func (this *PqUser) AdminAuth(password string) bool {
	o := GetSlaveDb()
	user := PqUser{Name : this.Name,Type:2}
	err := o.Read(&user,"Name","Type")
	if err == nil {
		pwd,_ := helper.Decrypt(user.Password,user.Salt)
		if pwd == password {
			return true
		}
	}
	return false
}
